package org.groupg.practice.Calc;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class Calculator {
    static final Logger log = LoggerFactory.getLogger(Calculator.class);
    public static void main(String[] args) throws Exception {
        // 输入字符串
        String input = "3 + 5 * 2";
        CharStream stream = CharStreams.fromString(input);

        // 1. 词法分析
        CalcLexer lexer = new CalcLexer(stream);
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // 2. 语法分析
        CalcParser parser = new CalcParser(tokens);
        ParseTree tree = parser.prog(); // 从 prog 规则开始解析

        // 动态禁用乘法
        parser.setEnableMultiplication(false);

        // 尝试解析会抛出错误，因为乘法已被禁用
        try {
            tree = parser.prog();
        } catch (Exception e) {
            log.error("解析失败: " + e.getMessage(),e);
        }
        // 3. 遍历语法树（使用访问者模式）
        CalcBaseVisitor<Integer> visitor = new CalcBaseVisitor<>() {
            @Override
            public Integer visitNumber(CalcParser.NumberContext ctx) {
                return Integer.parseInt(ctx.INT().getText());
            }

            @Override
            public Integer visitBinaryOp(CalcParser.BinaryOpContext ctx) {
                int left = visit(ctx.expr(0));  // 递归计算左子树
                int right = visit(ctx.expr(1)); // 递归计算右子树
                if (ctx.ADD() != null) {
                    return left + right;
                } else if (ctx.MUL() != null) {
                    return left * right;
                }
                throw new RuntimeException("未知运算符");
            }
        };

        int result = visitor.visit(tree);
        System.out.println("计算结果: " + result); // 输出 13 (3 + (5*2) = 13)
    }
}